package com.kanshu.ksgb.fastread.doudou.module.bookcity.view;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigs;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader;
import com.kanshu.ksgb.fastread.doudou.common.supertextview.SuperTextView;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.BookUtils;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.ItemRefreshBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.SelectedBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.presenter.BookCityPresenter;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.utils.BookCityUtils;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Action;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

import static com.kanshu.ksgb.fastread.doudou.app.constants.Constants.BookCityModuleType.TYPE_FEMALE_JINGDIAN;
import static com.kanshu.ksgb.fastread.doudou.app.constants.Constants.BookCityModuleType.TYPE_MALE_SIRENDINGZHI;
import static com.kanshu.ksgb.fastread.doudou.app.constants.Constants.BookCityModuleType.TYPE_SELECTED_BENZHOUQIANGTUI;
import static com.kanshu.ksgb.fastread.doudou.app.constants.Constants.BookCityModuleType.TYPE_SELECTED_ZHONGBANGTUIJIAN;
import static com.kanshu.ksgb.fastread.doudou.base.baseui.SwipeBackActivity.ACTION_DESTORY;

/**
 * Created by wcy on 18/5/15.
 */

public class AdSelectedOneLayout extends LinearLayout implements IRefresh<SelectedBean> {

    @BindView(R.id.label)
    TextView mLabel;
    @BindView(R.id.sub_title)
    TextView mSubTitle;
    @BindView(R.id.top_container)
    LinearLayout mTopContainer;
    @BindView(R.id.bottom_container)
    LinearLayout mBottomContainer;
    ItemRefreshBean mItemRefreshBean;
    @BindView(R.id.change_tip)
    ImageView mChangeTip;
    private String mType;
    private boolean mShowedAd;
    public Subject<Integer> lifeCyclerSubject = PublishSubject.create();
    BookCityPresenter presenter;
    HashMap<String, Boolean> mShowNormalDatas = new HashMap<>();

    public AdSelectedOneLayout(Context context) {
        super(context);
        init();
    }

    public AdSelectedOneLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AdSelectedOneLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        presenter = new BookCityPresenter(lifeCyclerSubject);
        setOrientation(VERTICAL);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_ad_selected_one_layout, this);
        ButterKnife.bind(view);
    }

    @Override
    public void refresh(SelectedBean selectedBean, Object object) {
        ItemRefreshBean item = (ItemRefreshBean) object;
        if (selectedBean == null || item == null) {
            return;
        }
        mItemRefreshBean = item;

        mLabel.setText(selectedBean.name);
        mType = selectedBean.type;
        mLabel.setCompoundDrawablesWithIntrinsicBounds(item.selectionIcon, 0, 0, 0);
        if (TextUtils.isEmpty(item.subTitle)) {
            DisplayUtils.gone(mSubTitle);
        } else {
            DisplayUtils.visible(mSubTitle);
            mSubTitle.setText(item.subTitle);
        }
        BookCityUtils.rotateCancel(mChangeTip);
        refreshUI(selectedBean);
    }

    @Override
    public void onError(int code, String desc) {
        BookCityUtils.rotateCancel(mChangeTip);
    }

    @Override
    public void reset() {
        if (mShowNormalDatas != null) {
            mShowNormalDatas.clear();
        }
    }

    private void refreshItem(int pos, LinearLayout container, BookInfo item) {
        Log.d("AdSelectedOneLayout", "type:" + mType);
        container.getChildAt(pos).setVisibility(View.VISIBLE);
        FrameLayout frameLayout = (FrameLayout) container.getChildAt(pos);
        LinearLayout layout = (LinearLayout) frameLayout.getChildAt(0);
        ImageView imageView = (ImageView) layout.getChildAt(0);
        TextView tv1 = (TextView) layout.getChildAt(1);
        SuperTextView tv2 = (SuperTextView) layout.getChildAt(2);
        GlideImageLoader.load(item.cover_url, imageView);
        tv1.setText(item.book_title);
        tv2.setText(BookUtils.getBookLabel(item));
        DisplayUtils.visible(imageView, tv1, tv2);
        layout.setOnClickListener(v -> {
            ARouterUtils.toActivity(ARouterConfig.BOOK_DETAIL, "book_id", item.book_id);

            takeIf(TYPE_SELECTED_ZHONGBANGTUIJIAN, () -> {
                AdPresenter.pvuvStatics(container == mBottomContainer ? pos + 3 : pos,
                        R.string.SCTUIJIAN1_POSITION1,
                        R.string.SCTUIJIAN1_POSITION2,
                        R.string.SCTUIJIAN1_POSITION3,
                        R.string.SCTUIJIAN1_POSITION4,
                        R.string.SCTUIJIAN1_POSITION5,
                        R.string.SCTUIJIAN1_POSITION6);
            });
            takeIf(TYPE_SELECTED_BENZHOUQIANGTUI, () -> {
                AdPresenter.pvuvStatics(container == mBottomContainer ? pos + 3 : pos,
                        R.string.SCTUIJIAN6_POSITION1,
                        R.string.SCTUIJIAN6_POSITION2,
                        R.string.SCTUIJIAN6_POSITION3,
                        R.string.SCTUIJIAN6_POSITION4,
                        R.string.SCTUIJIAN6_POSITION5,
                        R.string.SCTUIJIAN6_POSITION6);
            });
        });
        if (pos == 1) {
            Log.d("AdSelectedOneLayout", "pos = 1 childcount :" + container.getChildCount());
        }
        if (layout.getChildCount() > 3) {
            Log.d("AdSelectedOneLayout", "childcount > 3");
            layout.removeViewAt(3);
        }
    }

    private void refreshUI(SelectedBean selectedBean) {
        if (Utils.isEmptyList(selectedBean.list)) {
            DisplayUtils.gone(mTopContainer, mBottomContainer);
        } else {
            DisplayUtils.visible(mTopContainer, mBottomContainer);
            if (mShowNormalDatas.get(mType) == null
                    || !mShowNormalDatas.get(mType)) {
                for (int i = 0; i < mTopContainer.getChildCount(); i++) {
                    mTopContainer.getChildAt(i).setVisibility(INVISIBLE);
                }
                for (int i = 0; i < mBottomContainer.getChildCount(); i++) {
                    mBottomContainer.getChildAt(i).setVisibility(INVISIBLE);
                }
                if (selectedBean.list.size() <= 3) {
                    DisplayUtils.gone(mBottomContainer);
                }
                if (selectedBean.list.size() > 6) {
                    selectedBean.list = selectedBean.list.subList(0, 6);
                }
                for (int i = 0; i < selectedBean.list.size(); i++) {
                    if (i < 3) {
                        refreshItem(i, mTopContainer, selectedBean.list.get(i));
                    } else {
                        refreshItem(i - 3, mBottomContainer, selectedBean.list.get(i));
                    }
                }
                mShowNormalDatas.put(mType, true);
            }
            refreshAd(selectedBean);
        }
    }

    private void refreshAd(SelectedBean selectedBean) {
        // 私人定制广告配置
        if (isShowAd()) {
            int pos = 0;
            if (TextUtils.equals(mType, TYPE_MALE_SIRENDINGZHI)) {
                pos = 1;
            } else if (TextUtils.equals(mType, TYPE_FEMALE_JINGDIAN)) {
                pos = 1;
            } else if (TextUtils.equals(mType, TYPE_SELECTED_BENZHOUQIANGTUI)) {
                pos = 5;
            }
            refreshAdByPos(selectedBean, pos);
        }

    }

    private void refreshAdByPos(SelectedBean selectedBean, int pos) {
        if (selectedBean.list.size() < pos) {
            return;
        }
        LinearLayout container;
        if (pos > 3) {
            container = mBottomContainer;
            pos = pos - 3;
        } else {
            container = mTopContainer;
        }
        container.getChildAt(pos).setVisibility(VISIBLE);
        FrameLayout frameLayout = (FrameLayout) container.getChildAt(pos);
        final LinearLayout layout = (LinearLayout) frameLayout.getChildAt(0);
        if (layout.getChildCount() > 3) {
            for (int i = layout.getChildCount() - 1; i >= 3; i--) {
                layout.removeViewAt(i);
            }
        }
        ImageView imageView = (ImageView) layout.getChildAt(0);
        TextView tv1 = (TextView) layout.getChildAt(1);
        SuperTextView tv2 = (SuperTextView) layout.getChildAt(2);
        DisplayUtils.gone(imageView, tv1, tv2);
        int adPositionId = ADConfigBean.POSITION_MALE_SIRENDINGZHI_MP_4;
        if (TextUtils.equals(mType, TYPE_FEMALE_JINGDIAN)) {
            adPositionId = ADConfigBean.POSITION_FEMALE_JINGDIAN_NP_4;
        } else if (TextUtils.equals(mType, TYPE_SELECTED_BENZHOUQIANGTUI)) {
            adPositionId = ADConfigBean.POSITION_BENZHOUQIANGGUANGGAO_JX_5;
        }
        AdUtils.Companion.fetchAdUtil((Activity) getContext(), null, null, adPositionId, AdStyleBean.BOOK_COVER_STYLE, R.layout.item_ad_selected_one_item_layout, new BaseAdListener() {
            @Override
            public void onAdLoadSucceeded(@org.jetbrains.annotations.Nullable View view) {
                if (layout.getChildCount() > 3) {
                    for (int i = layout.getChildCount() - 1; i >= 3; i--) {
                        layout.removeViewAt(i);
                    }
                }
                LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                params.gravity = Gravity.CENTER_HORIZONTAL;
                layout.addView(view, params);
                Log.d("AdSelectedOneLayout", "layout childcount" + layout.getChildCount());
            }

            @Override
            public void onAdLoadFailed() {
                DisplayUtils.visible(imageView, tv1, tv2);
            }

            @Override
            public void onAdClicked() {
            }

            @Override
            public void onADClosed() {
            }

            @Override
            public void onBackAd(@NotNull Object ad) {
            }
        });
    }

    @OnClick(R.id.change_container)
    public void onViewClicked() {
        mShowNormalDatas.put(mType, false);
        BookCityUtils.rotate(mChangeTip);
        BookCityUtils.refreshModuleInfos(mItemRefreshBean, this, presenter);

        takeIf(TYPE_SELECTED_ZHONGBANGTUIJIAN, () -> {
            AdPresenter.pvuvStatics(R.string.SCTUIJIAN1_HUANYIHUAN);
        });

        takeIf(TYPE_SELECTED_BENZHOUQIANGTUI,()->{
            AdPresenter.pvuvStatics(R.string.SCTUIJIAN6_HUANYIHUAN);
        });
    }

    private boolean isShowAd() {
        return TextUtils.equals(mType, TYPE_MALE_SIRENDINGZHI) && ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_MALE_SIRENDINGZHI_MP_4)) != null
                ||
                TextUtils.equals(mType, TYPE_FEMALE_JINGDIAN) && ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_FEMALE_JINGDIAN_NP_4)) != null
                ||
                TextUtils.equals(mType, TYPE_SELECTED_BENZHOUQIANGTUI) && ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_BENZHOUQIANGGUANGGAO_JX_5)) != null;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        lifeCyclerSubject.onNext(ACTION_DESTORY);
    }


    /**
     * 检查 ItemRefreshBean.type 如果与 传入type 相同执行操作
     * {@link BookCityUtils#takeIf(ItemRefreshBean, String, Action)}
     */
    private void takeIf(String type, Action action) {
        BookCityUtils.takeIf(mItemRefreshBean, type, action);
    }

}
